package com.doodle.common.utils;

import android.util.Log;

public class TimeTracker {
	
	long mLap;
	long mCost;
	long mBegin;
	long mId;
	long mMax;
	long mCount;
	String mTag;
	
	private static int mTaskCounter = 0;

	public TimeTracker(String tag) {
		mLap = 0;
		mTag = tag;
	}
	
	public void begin(long id) {
		++mTaskCounter;
		if (mTaskCounter != 1) {
			Log.e(mTag, "mTaskCounter: begin: " + mTaskCounter + ", id: " + mId);
		}
		mId = id;
		mBegin = System.currentTimeMillis();
		if (mLap == 0) {
			mLap = mBegin;
			mCost = 0;
    		mMax = -1;
    		mCount = 0;
		}
	}
	
	public void end() {
		--mTaskCounter;
		if (mTaskCounter != 0) {
			Log.e(mTag, "mTaskCounter: end: " + mTaskCounter + ", id: " + mId);
		}
		++mCount;
		long endTick = System.currentTimeMillis();
		long diff = endTick - mBegin;
		if (diff > 10) {
			Log.d(mTag, "End:" + mId + ": " + diff);
		}
		mCost += diff;
		if (mMax < diff) {
			mMax = diff;
		}
		if (mCost > 1000) {
			long elapsed = endTick - mLap;
			Log.d(mTag, "TimeCost percent:" + mId + ": " + mCost * 100 / elapsed
					+ ", max: " + mMax
					+ ", avg: " + (mCost / mCount)
					+ ", freq: " + (mCount * 1000 / elapsed));
			mLap = 0;
		}
	}
}